<template>
	<el-dialog title="发布动态" center :destroyOnClose='true' :show-close="true" @close="handleClosed" :fullscreen="true"
		:visible="isshow" :modal="false">
		<div class="contentBox">
			<el-input type="textarea" :autosize="{ minRows: 1,maxRows:45}" resize='none' :maxlength='contentMaxlength'
				:placeholder="placeholderTip" @blur="handledCache" v-model="state.content"
				style="vertical-align: middle;margin-top: 5px;">
			</el-input>
			<div class="">

				<div class="stateImagesBox1" v-viewer="{url: 'data-src' }">
					<draggable v-model="imageslist" chosenClass="chosen" forceFallback="true" group="imagesState"
						animation="1000" @start="onStart" @end="onEnd" style="width: 100%;">
						<transition-group class="stateImagesBox">
							<template v-for="item,index in imageslist">
								<div class="stateImages" :key="`images${item.uniqueID}`">
									<video-play v-if="item.type=='video/mp4'" :imagesItem='item'
										:isDelayFlag="false"></video-play>
									<img v-else :src="`${item.path}?w=148&h=148&q=75`" :data-src="item.path"
										class="item" style="object-fit:cover;" />
									<span @click="handledCancel(item.uniqueID)"
										class="upload-cancel cursorPointer">X</span>
								</div>
							</template>
						</transition-group>
					</draggable>
					<div class="font12 color-smill">{{imageslist.length>1?'支持拖拽':''}}</div>
					<!-- <template v-for="item,index in imageslist">
						<div class="stateImages" :key="`images${item.uniqueID}`">
							<video-play v-if="item.type=='video/mp4'" :imagesItem='item'
								:isDelayFlag="false"></video-play>
							<img v-else :src="`${item.path}?w=148&h=148&q=75`" :data-src="item.path" class="item"
								style="object-fit:cover;" />
							<span @click="handledCancel(item.uniqueID)" class="upload-cancel cursorPointer">X</span>
						</div>
					</template> -->
				</div>
				<multi-upload class="multiUpload" v-model="imageslist" :disable="imageslistUpload"
					:maxUploadCount="maxUpload"></multi-upload>
				<div class="">
					<el-tag :key="tag" v-for="tag in stateTags" closable class="state-tag" :disable-transitions="false"
						@close="tagRemove(tag)">{{tag}}</el-tag>
					<el-input class="input-new-tag" v-if="inputVisible" v-model="inputTag" ref="saveTagInputState"
						size="small" maxlength="15" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm"
						οnkeyup="value=value.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')"
						οnpaste="value=value.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')"
						oncontextmenu="value=value.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')">
					</el-input>
					<el-button v-else-if="stateTags.length!=tagMaxNumber" class="button-new-tag" size="small"
						@click="showInput">添加标签</el-button>
				</div>
				<div class="">
					<el-select v-model="state.Visibility" placeholder="可见范围" size="small"
						style="width: 150px;margin: 10px 0;">
						<el-option v-for="item in Visibilitys" :key="item.value" :label="item.label"
							:value="item.value">
						</el-option>
					</el-select>
				</div>
			</div>
		</div>
		<el-dialog center title="提示" :visible.sync="contentVisible" width="75%" :modal="false" :show-close="false"
			:close-on-click-modal="false">
			<span>有数据未发表，是否继续编辑？</span>
			<span slot="footer" class="dialog-footer">
				<el-button @click="handledCancelEdit">取 消</el-button>
				<el-button type="primary" @click="handledOkEdit">确 定</el-button>
			</span>
		</el-dialog>
		<div class="dialog-footer-state">
			<el-button class="add" type="primary" @click="handleAdd" v-loading="loading">发布</el-button>
		</div>
		<sensitive-words-v ref="sensitiveWordsVRef"></sensitive-words-v>
	</el-dialog>
</template>

<script>
	//导入draggable组件
	import draggable from 'vuedraggable'
	import {
		imageNowIP
	} from "@/utils/config"
	import {
		getType
	} from "@/utils/base";
	import {
		addState
	} from "@/api/state"
	import {
		debounce
	} from "@/utils/common.js";
	import multiUpload from "@/components/Upload/multiUpload"
	import VideoPlay from "@/components/VideoPlay"
	import sensitiveWordsV from "@/components/sensitiveWordsV/sensitiveWordsV"
	export default {
		name: "pageStateAddMobile",
		components: {
			multiUpload,
			VideoPlay,
			draggable,
			sensitiveWordsV
		},
		props: {
			isshow: {
				type: Boolean,
				default: false

			}
		},
		data() {
			return {
				drag: false, //拖拽标识
				imageNowIP: imageNowIP,
				contentVisible: false, //提示是否有数据可编辑
				EditData: {}, //可编辑数据 容器
				loading: false,
				contentMaxlength: 5000,
				placeholderTip: "给心腾点空间，记录自己~",
				tagMaxNumber: 5,
				inputVisible: false,
				inputTag: "",
				imageslist: [], //图像 发布时转json
				stateTags: [], // 标签 发布时转json
				state: {
					content: "",
					images: "",
					stateTags: "",
					Visibility: 1, //可见范围
				},
				maxUpload: 12, //最大上传文件个数
				Visibilitys: [{
					value: 1,
					label: "全部"
				}, {
					value: 2,
					label: "好友可见"
				}, {
					value: 3,
					label: "私密"
				}]
			}
		},
		mounted() {},
		computed: {
			storeUserinfo() {
				return this.$store.getters.userInfo
			},
			imageslistUpload() {
				try {
					return this.imageslist.length == this.maxUpload
				} catch (e) {
					return false
				}
			},

		},
		methods: {
			//开始拖拽事件
			onStart() {
				this.drag = true;
			},
			//拖拽结束事件
			onEnd() {
				this.drag = false;
			},
			//标签输入框
			showInput() {
				this.inputVisible = true;
				this.$nextTick(_ => {
					this.$refs.saveTagInputState.$refs.input.focus();
				});
			},
			// 标签移除
			tagRemove(tag) {
				this.stateTags.splice(this.stateTags.indexOf(tag), 1);
			},
			// 新增确认
			handleInputConfirm(val, type) {
				let that = this;
				let inputTag = that.inputTag || val;
				if (!inputTag || getType(inputTag).indexOf('event') != -1) {
					that.inputVisible = false;
					that.inputTag = "";
					return
				}
				//正则匹配
				inputTag = inputTag.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g, '')
				try {
					that.stateTags.forEach((item, index, array) => {
						if ("#" + inputTag == item) {
							that.$message({
								message: "已存在相同标签，换一个试试吧",
								type: "warning",
								duration: 700
							})
							throw new Error('beng~')
						}
					})
					if (inputTag) {
						that.stateTags.push("#" + inputTag);
						let array = new Set(that.stateTags);
						let newArr = Array.from(array)
						if (newArr.length != that.stateTags.length) {
							that.stateTags = newArr
						}

					}
					that.inputVisible = false;
					that.inputTag = "";
					this.handledCache()
				} catch (e) {}
			},
			//关闭
			handleClosed(config = {
				status: 3
			}) {
				this.$emit("shsClose", config)
			},
			async handledCache() {
				await this.haveData()
				localStorage.setItem("stateAdd", JSON.stringify(this.state))
			},
			haveData() {
				const transformedList = this.imageslist.map(value => ({
					type: value.type,
					path: value.path,
					dirPath: value.dirPath,
					thumbnail: value.thumbnail,
					m3u8path: value.m3u8path,
					uniqueID: value.uniqueID
				}));
				this.state.images = transformedList.length > 0 ? JSON.stringify(transformedList) : "";
				this.state.stateTags = this.stateTags.toString();
			},
			//发表
			handleAdd: debounce(async function() {
				await this.haveData();
				if (!this.state.images.trim() && !this.state.content.trim()) {
					this.$message({
						message: "不能发布空消息",
						type: 'warning',
						duration: 700
					});
					return;
				}
				addState(this.state).then(res => {
					this.$message({
						showClose: true,
						message: res.message,
						type: 'success',
						duration: 3000
					});
					this.handleClosed({
						status: res.status,
						Visibility: this.state.Visibility
					})
					this.initdata();
				}, (err) => {
					try {
						if(err.message=='存在敏感词，请修改后再发布'){
							this.$refs['sensitiveWordsVRef'].initData({highlightedText:err.highlightedText}) 
						}
					} catch (error) {
						//TODO handle the exception
						console.log(error);
					}
				})

			}),
			initdata() {
				this.state = {
					content: "",
					images: "",
					stateTags: "",
					Visibility: 1
				}
				this.stateTags = []
				this.imageslist = []
			},
			handledCancel(uniqueID) {
				this.imageslist = this.imageslist.filter(function(item, index, arr) {
					return item.uniqueID != uniqueID
				}, this)

			},
			//继续编辑
			handledOkEdit() {
				try {
					this.state.content = this.EditData.content || "";
					this.state.Visibility = this.EditData.Visibility || 1;
					this.stateTags = this.EditData.stateTags ? this.EditData.stateTags.split(',') : [];
					this.imageslist = this.EditData.images ? JSON.parse(this.EditData.images) : [];
					this.contentVisible = false
				} catch (e) {
					this.initdata()
				}
			},
			//取消编辑
			handledCancelEdit() {
				this.initdata()
				this.contentVisible = false
			}
		},
		watch: {
			isshow: {
				deep: true, // 深度监听
				immediate: true, // 页面初始化时是否触发回调
				handler: function(value, oldVal) {
					try {
						if (value) {
							//获取缓存数据
							let data = JSON.parse(localStorage.getItem("stateAdd"))
							if (data && (data.content != "" || data.images != "" || data.stateTags != "")) {
								this.EditData = data
								this.contentVisible = true;
							}
						}
					} catch (e) {}
				}
			},
			"state.Visibility": {
				deep: true, // 深度监听
				immediate: false, // 页面初始化时是否触发回调
				handler: function(value, oldVal) {
					try {
						if (value) {
							this.state.Visibility = value
							this.handledCache()
						}
					} catch (e) {}
				}
			},
			imageslist: {
				deep: true, // 深度监听
				immediate: true, // 页面初始化时是否触发回调
				handler: function(value, oldVal) {
					try {
						if (value.length > 0) {
							this.handledCache()
						}
					} catch (e) {}
				}
			},
			storeUserinfo: {
				deep: true, // 深度监听
				immediate: true, // 页面初始化时是否触发回调
				handler: function(value, oldVal) {
					if (!value.Id) {
						return
					}
					if (value.isAdmin) {
						//特权用户
						this.$nextTick(() => {
							this.contentMaxlength = 8000
							this.maxUpload = 18
						})
					}



				}
			},

		}
	}
</script>

<style scoped>
	.item {
		padding: 1px;
		background-color: #fdfdfd;
		border: solid 1px #eee;
		margin-bottom: 10px;
		cursor: move;
	}

	/*选中样式*/
	.chosen {
		box-sizing: border-box;
		border: solid 2px #3089dc !important;
	}



	.state-tag {
		margin: 2px;
		margin-right: 10px;
	}

	.input-new-tag {
		width: 90px;
		margin: 2px;
		vertical-align: bottom;
	}

	.contentBox {
		box-shadow: 2px 2px 10px #00aaff;
		position: fixed;
		width: calc(100vw - 50px);
		height: calc(100vh - 120px);
		overflow-y: auto;
		overflow-x: hidden;
		margin: 0;
		padding: 0 2px;
		box-sizing: border-box;
		border-radius: 12px;
	}

	.dialog-footer-state {
		position: fixed;
		bottom: 10px;
		margin: 0;
		padding: 0;
		width: calc(100vw - 50px);
		height: 45px;
		line-height: 45px;
		text-align: center;

	}

	.dialog-footer-state .add {
		width: 100%;
		border-radius: 18px;
	}

	.multiUpload {
		width: 100%;
		margin: 22px 0;
	}

	.stateImagesBox {
		width: 100%;
		position: relative;
		display: flex;
		justify-content: flex-start;
		align-items: center;
		flex-wrap: wrap;
		flex-direction: row;
	}

	.stateImagesBox .stateImages {
		width: calc(100%/2);
		height: 148px;
		padding: 1px;
		box-sizing: border-box;
		position: relative;
	}

	.stateImagesBox .stateImages .item {
		width: 100%;
		height: 100%;
		margin: 0;
		padding: 0;
	}

	.upload-cancel {
		float: right;
		display: inline-block;
		position: absolute;
		text-align: center;
		width: 25px;
		height: 25px;
		line-height: 25px;
		top: 0;
		right: -5px;
		border-radius: 50%;
		z-index: 2222;
		background: rgba(139, 139, 139, 1.0);
		color: #fff;
	}
</style>